<?php echo $this->element('displayHeader'); ?>
<?php echo $ajax->form('SDH', 'post', array('update'=>'content', 'indicator' => 'indicator', 'url' => array('action' => 'save')));?>
<div class="toolbar">
    <div id="tLeft">
        <?php if ($mode == 'add' || $mode == 'revise') : ?>
            <?php echo $this->element('toolbar', array('buttons' => array('save', 'clear', 'back'))); ?>
        <?php elseif (isset($canRevise)) :  // On Dispatch revise ได้ ?>
            <?php echo $this->element('toolbar', array('buttons' => array('add',
                    array('edit' => array('text' => 'Revise', 'params' => $this->data['SDH']['id'] . "/revise:true")),
                    array('print' => array('model' => 'SDH')), array('print_cust' => array('model' => 'SDH')), 'back'))); ?>
        <?php else :  // mode edit ?>
            <?php echo $this->element('toolbar', array('buttons' => array('add', array('print' => array('model' => 'SDH')), array('print_cust' => array('model' => 'SDH')), 'back'))); ?>
        <?php endif; ?>
    </div>
    <div id="tRight"><?php echo $this->element('neighbors', array('model' => 'SDH', 'title' => 'dispatch_no')); ?></div>
</div>

<?php echo $form->input('SDH.id'); ?>
<?php echo $form->hidden('mode', array('value' => $mode)); ?>
<?php if ($mode == 'revise') echo $form->hidden('SDH.old_id'); ?>
<fieldset>
    <table>
        <tr>
            <td width="120px"><?php echo $form->label('SDH.supplier_id', 'Vendor'); ?></td>
            <td width="300px">
                <?php if ($mode == 'add') : ?>
                    <?php echo $supplierName; ?>
                <?php else : ?>
                    <?php echo $this->data['Supplier']['name'] ?>
                <?php endif; ?>
            </td>
            <td width="120px"><?php echo $form->label('SDH.customer_id', 'Customer', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('SDH.customer_id', array('id' => 'hidSDHCustomerId')); ?>
                    <?php echo $form->select('SDH.customer_id', $customers); ?>
                <?php else : ?>
                    <?php echo $form->hidden('SDH.customer_id'); ?>
                <span id="customer_id"><?php echo $this->data['Customer']['name'] ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('SDH.dispatch_no', 'Dispatch no.'); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                &nbsp;
                <?php else : ?>
                <span id="dispatch_no"><?php echo $this->data['SDH']['dispatch_no'] ?></span>
                    <?php echo $form->hidden('SDH.dispatch_no'); ?>
                <?php endif; ?>
            </td>
            <td><?php echo $form->label('SDH.site_id', 'Site', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('SDH.site_id', array('id' => 'hidSDHSiteId')); ?>
                    <?php echo $form->select('SDH.site_id'); ?>
                <?php else : ?>
                    <?php echo $form->hidden('SDH.site_id'); ?>
                <span id="site_id"><?php echo $this->data['Site']['name']; ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('SDH.dispatch_date', 'Dispatch date', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <?php echo $form->text('SDH.dispatch_date', array('tabindex' => 1)); ?>
                <?php else : ?>
                <span id="dispatch_date"><?php echo $this->data['SDH']['dispatch_date'] ?></span>
                <?php endif; ?>
            </td>
            <td><?php echo $form->label('SDH.to_warehouse', 'To Warehouse', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <?php echo $form->text('SDH.to_warehouse', array('tabindex' => 7)); ?>
                <?php else : ?>
                <span><?php echo $this->data['SDH']['to_warehouse'] ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><label for="SDHSDHStatusId">Dispatch Status</label></td>
            <td>
                <?php if ($mode == 'edit') {
                    echo $this->data['DispatchStatus']['title'];
                } else {
                    echo $dispatchStatus;
                } ?>
            </td>
            <td><?php echo $form->label('SDH.delivered_to', 'Delivered To', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <?php echo $form->text('SDH.delivered_to', array('tabindex' => 8)); ?>
                <?php else : ?>
                    <?php echo $this->data['SDH']['delivered_to'] ?>
                <?php endif; ?>
            </td>
        </tr>
    </table>
</fieldset>

<fieldset>
    <table class="data">
        <thead>
            <tr>
                <th class="no">No</th>
                <th width="200">Part no.</th>
                <th width="135px">Stock code</th>
                <th>Description</th>
                <th width="40px">Qty</th>
                <th width="50px">Unit</th>
                <th width="80px">Price/Unit</th>
                <th width="75px">Amount</th>
                <th width="50px">Index</th>
                <?php if($mode == 'add' || $mode == 'revise') : ?>
                <th class="action">&nbsp;</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody id="productRow">
            <?php if ($mode == 'add') : ?>
            <?php else :
                $count = count($this->data['SD']);
                $total = 0;
            ?>
                <?php for($i = 0; $i < $count; ++$i) : ?>
            <tr class="<?php echo (($i + 1) % 2 == 0)? 'even-cell' : 'odd-cell'; ?> center">
                <td><span><?php echo $i + 1; ?></span></td>
                <td>
                            <?php echo $html->link($this->data['SD'][$i]['Product']['supplier_part_no'],
                            '/supplier_consignment_lists/view/' . $this->data['SD'][$i]['product_id'] . '/' . strtotime('now'),
                            array('target' => '_blank')); ?>
                    <span id="spanSD<?php echo $i; ?>PartNo" style="display: none"><?php echo $this->data['SD'][$i]['Product']['supplier_part_no']; ?></span>
                            <?php echo $form->hidden("SD.{$i}.product_id"); ?>
                            <?php echo $form->hidden("SD.{$i}.cust_product_site_id"); ?>
                </td>
                <td><?php echo $this->data['SD'][$i]['CPS']['stock_code']; ?></td>
                <td class="text-left"><?php echo !empty($this->data['SD'][$i]['CPS']['text'])?
                $this->data['SD'][$i]['CPS']['text']:
                $this->data['SD'][$i]['Product']['text']; ?></td>
                <td class="text-right">
                            <?php if ($mode == 'revise') : ?>
                                <?php echo $form->text("SD.{$i}.qty", array('size' => 3, 'class' => 'text-right', 'no' => $i)); ?>
                            <?php else : ?>
                                <?php echo $this->data['SD'][$i]['qty']; ?>
                            <?php endif; ?>
                </td>
                <td class="center">
                            <?php echo $this->data['SD'][$i]['Product']['Unit']['title']; ?>
                </td>
                <td class="text-right">
                    <span id="spanSD<?php echo $i; ?>Price"><?php echo number_format($this->data['SD'][$i]['price'], 2); ?></span>
                            <?php echo $form->hidden("SD.{$i}.price"); ?>
                </td>
                <td class="text-right">
                    <span id="spanSD<?php echo $i; ?>Amount">
                    <?php
                    $amount = $this->data['SD'][$i]['price'] * $this->data['SD'][$i]['qty'];
                    $total += $amount;
                    echo number_format($amount, 2); ?>
                    </span>
                </td>
                        <?php if ($mode == 'edit') : ?>
                <td class="center">
                                <?php echo $ajax->link($html->image('icon/popup.png', array('alt' => 'Serial information')),
                                array('controller' => 'products_serials', 'action' => 'popup_view', $this->data['SD'][$i]['product_id'] . '/' . 'its_stock_out_id:' . $this->data['SD'][$i]['id'] . '/its_stock_out_type:' . SD::ITS_STOCK_OUT_TYPE),
                                array('update' => 'content', 'position' => 'bottom', 'indicator' => 'indicator' ), null, false); ?>
                </td>
                        <?php else : ?>
                <td class="center" id="tdIndex<?php echo $i; ?>">
                    <a href="#" id="SD<?php echo $i; ?>Index" no="<?php echo $i; ?>"><?php echo $html->image('icon/popup.png', array('title' => 'Index', 'alt' => 'Index')); ?></a>
                    <div id="Index<?php echo $i; ?>" style="display: none;"></div><div id="popupIndex<?php echo $i; ?>"></div>
                </td>
                <td class="center"><a href="#" id="linkSD<?php echo $i; ?>Delete" style="display: none;"><?php echo $html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')); ?></a></td>
                        <?php endif; ?>
            </tr>
                <?php endfor; ?>
            <?php endif; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="7" class="text-right">Total</td>
                <td class="text-right">
                    <span id="spanTotal">
                        <?php if ($mode != 'add') echo number_format($total, 2); ?>
                    </span>
                </td>
                <td <?php if ($mode != 'edit') echo 'colspan="2"'; ?>>&nbsp;</td>
            </tr>
        </tfoot>
    </table>
</fieldset>
<fieldset>
    <table>
        <tr>
            <td width="50px" class="top"><?php echo $form->label('SDH.remark'); ?></td>
            <td>
            <?php if ($mode == 'add' || $mode == 'revise') : ?>
                <?php echo $form->textarea('SDH.remark', array('cols' => 80, 'rows' => 3)); ?>
            <?php else : ?>
                <?php echo empty($this->data['SDH']['remark'])? '-': $this->data['SDH']['remark']; ?>
            <?php endif; ?>
            </td>
        </tr>
    </table>
</fieldset>

<?php echo $form->end(); ?>

<?php if ($mode == 'add' || $mode == 'revise') : ?>
<script type="text/javascript">

    var mode = $j('#mode').val();

    // JSON เก็บ part no ที่ป้อนเข้ามา อ้างไปยังลำดับแถว
    var partNos = {};

    requestProduct = function(event) {
        var e = $j(event.target);
        var no = e.attr("no");  // ลำดับแถวปัจจุบัน เริ่มที่ 0
        var part_no = $j.trim(e.val().toUpperCase());  // part no ที่ใส่เข้ามา

        // ไม่ได้ใส่อะไรเข้ามา
        if(part_no.length == 0) { return; }

        if (mode == 'add') {
            if ($j("#SDHSiteId").val() == "") {
                alert("Please select a customer site.");
                e.val('');  // clear field
                return;
            } else {
                $j("#SDHCustomerId").attr('disabled', true);
                $j("#SDHSiteId").attr('disabled', true);
                $j("#hidSDHCustomerId").val($j("#SDHCustomerId").val());
                $j("#hidSDHSiteId").val($j("#SDHSiteId").val());
            }
        }

        // ถ้ายังไม่มี part no นี้อยู่
        if (partNos[part_no] == null) {
            var url = base + "/supplier_dispatches/json_find_by_part_no_site_id/";
            var params = {part_no: part_no, site_id: $j("#SDHSiteId").val()};
            postRequest(url, params, function(data) {
                if (data.CPS) { // มีทั้ง CustProductSite และ product
                    // Product นี้ไม่ได้ consigned โดย Supplier
                    if (data.CPS.dispatch_from == 'its' && data.CPS.current_stock > 0) {
                        alert("You can not dispatch this product.");
                        e.val('').focus();
                    } else {
                        // ถ้า CPS นี้ยกเลิกการใช้งานแล้วจะ dispatch ไปให้ไม่ได้
                        if (data.CPS.discontinued == true) {
                            alert("This product has been discontinued for this customer.<br />\n\
                              Please contract VMI section at <?php echo $this->requestAction('system_preferences/get/company_name'); ?><br />\
                              tel. <?php echo $this->requestAction('system_preferences/get/tel'); ?>");
                            e.val('').focus();
                            return;
                        }
                        if (data.CPS.text != null) {
                            $j("#SD" + no + "Text").text(data.CPS.text);
                        }
                        $j("#SD" + no + "StockCode").text(data.CPS.stock_code);
                        $j("#SD" + no + "CustProductSiteId").val(data.CPS.id);
                        $j("#SD" + no + "Price").val(data.CPS.price? data.CPS.price: 0);
                        $j("#spanSD" + no + "Price").text(data.CPS.price? data.CPS.price: '0');
                        setSD(data, part_no, no);
                    }

                } else if (data.Product) { // มี product อย่างเดียว (ยังไม่ได้ add stock code)
                    alert("You cann't dispatch this product at this time.<br />\n\
                              Please contract VMI section at <?php echo $this->requestAction('system_preferences/get/company_name'); ?><br />\
                              tel. <?php echo $this->requestAction('system_preferences/get/tel'); ?>");
                    e.val('').focus();
                } else { // ไม่พบข้อมูล (กรอกข้อมูลผิด...)
                    alert("No product found.");
                    createSerialElement(no);
                    e.val('').focus();
                }
            }
        );
        } else {
            e.val('');
            var row = partNos[part_no]; // แถวที่มี part_no นี้อยู่
            $j("#SD" + row + "Qty").val(parseInt($j("#SD" + row + "Qty").val()) + 1);
            calAmount(row);
            setTimeout(function() { $j("#SD" + no + "PartNo").focus(); }, 100);
        }
    }

    function createSerialElement(row) {
        var divIndex = $("Index" + row)
        var stock_in_qty = $F("SD" + row + "Qty");
        divIndex.update("");
        var runno = 1;
        var index = 0;
        $j("#popupIndex" + row).dialog("option", "title", "Serial no. for " + $("spanSD" + row + "PartNo").innerHTML + ". (If available)");
        var table = new Element('table', {'class': 'data', 'id': 'table' + row});
        var thead = new Element('thead');
        var tr = new Element('tr');

        tr.update(new Element('th', {width: 35}).update('No.'));
        tr.insert(new Element('th', {width: 120}).update('Serial no.'));
        tr.insert(new Element('th'/*, {width: 200}*/).update('Other Information'));
        thead.update(tr);
        table.insert(thead);
        var tbody = new Element('tbody');
        table.insert(tbody);
        divIndex.insert(table);
        $R(0, stock_in_qty, true).each(function() {
            var tr = new Element('tr');
            var tdNo = new Element('td', {'class': 'center'});
            tdNo.update(runno);
            tdNo.insert('<input type="hidden" id="Product' + row + 'Serial' + index + 'Id" name="data[SD][' + row + '][ProductSerial][' + index + '][id]" value="" />');
            tr.insert(tdNo);

            var tdSerial = new Element('td');
            tdSerial.update('<input type="text" id="Product' + row + 'Serial' + index + 'SerialNo" name="data[SD][' + row + '][ProductSerial][' + index + '][serial_no]" size="15" />');
            tr.insert(tdSerial);

            var tdOtherIn = new Element('td', {'class': 'center'});
            tdOtherIn.update('<textarea id="Product' + row + 'Serial' + index + 'OherInformation" name="data[SD][' + row + '][ProductSerial][' + index + '][other_information]" rows="2" style="width: 95%"></textarea>');
            tr.insert(tdOtherIn);

            tbody.insert(tr);
            runno++; index++;
        });
    }

    setSD = function(data, part_no, no) {

        $j("#SD" + no + "Text").text(data.Product.text);
        $j("#SD" + no + "PartNo").hide();
        $j("#linkSD" + no + "ProductId").hide();
        $j("#spanSD" + no + "PartNo").text(data.Product.supplier_part_no);
        $j("#SD" + no + "ProductId").val(data.Product.id);
        $j("#SD" + no + "Unit").text(data.Product.Unit.title);
        $j("#SD" + no + "Qty").val(1);

        linkDelete(no);

        partNos[part_no] = no;  // บันทึกแถวปัจจุบันของ part no
        calAmount(no);
        var nextRow = parseInt(no) + 1;
        createRow(nextRow);
        $j("#SD" + nextRow + "PartNo").focus();
    }

    calAmount = function(no) {
        var qty = parseInt($j("#SD" + no + "Qty").val());
        var price = parseFloat($j("#SD" + no + "Price").val());
        var amount = qty * price;
        $j("#SD" + no + "Amount").text(amount.toFixed(2));

        var total = 0;
        // calculate total
        $j('span[id$=Amount]').each(function() {
            var amount = parseFloat($j.trim($j(this).html()).replace(',', ''));
            if (!isNaN(amount)) {
                total += amount;
            }
        });
        $j('#spanTotal').html(total.toFixed(2));

        createSerialElement(no);
    }

    productsHandler = function(part_no) {
        if (part_no != null) {
            // หา input part no ที่ยังแสดงอยู่ (มีอันเดียวเสมอ)
            if ($j.browser.msie == true) {
                $j("input[id$=PartNo]:visible").val(part_no).focus();
            } else {
                $j("input[id$=PartNo]:visible").val(part_no).focus().blur();
            }
        }
    }

    createRow = function(row, data) {
        var tr = $j("<tr>").attr({no: row}).addClass(((row + 1) % 2 == 0)? "even-cell" : "odd-cell")
        .append($j("<td class='center'>&nbsp;</td>"))
        .append($j('<td><span id="spanSD' + row + 'PartNo"></span></td>')
        .append('<input id="SD' + row + 'PartNo" type="text" value="" no="' + row + '" />')
        .append('<input id="SD' + row + 'ProductId" type="hidden" value="" name="data[SD][' + row + '][product_id]"/>')
        .append('<input id="SD' + row + 'CustProductSiteId" type="hidden" value="" name="data[SD][' + row + '][cust_product_site_id]"/>')
        .append('&nbsp;<a href="#" id="linkSD' + row + 'ProductId"><?php echo $html->image('icon/search.png'); ?></a>'))
        .append($j('<td><span id="SD' + row + 'StockCode"></span></td>'))
        .append($j('<td><span id="SD' + row + 'Text"></span></td>'))
        .append($j('<td></td>').addClass('text-right')
        .append('<input id="SD' + row + 'Qty" no="' + row + '" type="text" size="3" class="text-right" value="" name="data[SD][' + row + '][qty]"/>'))
        .append($j('<td><span id="SD' + row + 'Unit"></span></td>').addClass('center'))
        .append($j('<td></td>').addClass('text-right')
        .append('<input id="SD' + row + 'Price" no="' + row + '" type="hidden" value="" size="7" class="text-right" name="data[SD][' + row + '][price]"/><span id="spanSD' + row + 'Price"></span>'))
        .append($j('<td><span id="SD' + row + 'Amount"></span></td>').addClass('text-right'));
        tr.append($j('<td id="tdIndex' + row + '"><a href="#" id="SD' + row + 'Index" no="' + row + '"><?php echo $html->image('icon/popup.png', array('title' => 'Index', 'alt' => 'Index')); ?></a><div id="Index' + row + '" style="display: none;"></div><div id="popupIndex' + row + '"></div></td>').addClass('center'))
        tr.append($j('<td><a href="#" id="linkSD' + row + 'Delete" style="display: none;"><?php echo $html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')); ?></a></td>').addClass('center'));
        tr.appendTo("#productRow");
        $j('#productRow').runno();

        addRowListener(row);
    };

    addRowListener = function(row, revise) {
        // addListener
        if (revise != true) {
            $j("#SD" + row + "PartNo").bind('keypress', partNoKeyPress);
            $j("#SD" + row + "PartNo").bind('blur', function(event) {
                requestProduct(event);
            });
        }

        $j("#linkSD" + row + "ProductId").bind('click', function(event) {
            if ($j("#SDHSiteId").val() == "") {
                alert("Please select a customer site.");
                return;
            }

            var url = base + "/supplier_consignment_lists/popup_view";

            url += "/site_id:" + $j('#SDHSiteId').val();

            requestPopup(url, "productsHandler");
        });

        $j("#SD" + row + "Index").bind('click', function(event) {
            popupIndex($j(this).attr("no"));
        });
        initPopUpIndex(row);

        $j("#SD" + row + "Qty").bind('keypress', stopKeyEnter);
        $j("#SD" + row + "Qty").bind('change', function(event) {
            calAmount($j(this).attr("no"));
        });

    };

    linkDelete = function(no) {
        // ดักจับ Event กดลบแถว
        $j('#linkSD' + no + 'Delete').bind('click', function() {
            // ลบรายการ part no ออกจาก list
            var p = $j("#spanSD" + no + "PartNo").text();
            partNos[p] = undefined;

            // ลบ แถว
            $j('#spanSD' + no + 'PartNo').parents('tr').remove();

            // จัดลำดับตัวเลขหน้าแถวใหม่
            $j('#productRow').runno();
        }).show();
    }

    $j(function() {

        /**
         * validate ข้อมูลด้วย javascript ก่อน
         */
        $j('#SDHId').parent('form').beforeSubmit(function() {
            if ($j.areEmpty('SDHDispatchDate', 'SDHCustomerId', 'SDHSiteId', 'SDHToWarehouse', 'SDHDeliveredTo')) {
                return false;
            }

            if (!$j.validateColumns('ProductId', 'Product', {callback: $j.EMPTY})) {
                return false;
            }

            if (!$j.validateColumns('Qty', 'Qty', {callback: $j.QTY})) {
                return false;
            }
            return true;
        });

        $j('#SDHDispatchDate').datepicker(datepicker_options);

        if (mode == 'revise') {

            var tr = $j('#productRow').children();
            tr.each(function(i) {
                partNos[$j('#spanSD' + i + 'PartNo').text()] = i;  // บันทึกแถวปัจจุบันของ part no
                addRowListener(i, true);
                linkDelete(i);
                calAmount(i);
            });
        } else {
            $j("#SDHCustomerId").bind('change', function() {
                requestOptions("sites", "SDHCustomerId", "SDHSiteId");
            })
        }

        createRow($j('#productRow').children().length);
    })
</script>
<?php endif; ?>